package com.cma.cmabackend.service;

import com.cma.cmabackend.dao.CategoryDao;
import com.cma.cmabackend.entity.Category;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Service
public class CategoryService {
    @Resource
    CategoryDao categoryDao;

    public boolean isExist(String category) {
        Category category1 = categoryDao.findByCategoryName(category);
        return category1 != null;
    }

    public Category addCategory(String category) {
        Category category1 = new Category();
        category1.setCategoryName(category);
        category1.setTypes(new ArrayList<>());
        categoryDao.save(category1);
        return category1;
    }

    public int getCategoryIdOrAdd(String category) {
        if (!isExist(category)) {
            return addCategory(category).getId();
        } else {
            Category category1 = categoryDao.findByCategoryName(category);
            return category1.getId();
        }
    }

    public Category findCategoryByName(String category) {
        return categoryDao.findByCategoryName(category);
    }

    public String getCategoryNameById(int id) {
        return Objects.requireNonNull(categoryDao.findById(id).orElse(null)).getCategoryName();
    }

    public List<Category> getAll() {
        return categoryDao.findAll();
    }

    public Category save(Category category) {
        return categoryDao.save(category);
    }
}
